package com.jinxin.platform.cdqzsqacs.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.InvokeCfg;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.base.common.support.BusinessDelegate;
import com.jinxin.platform.cdqzsqacs.bean.*;
import com.jinxin.platform.cdqzsqacs.bean.bo.ParsedDownResult;
import com.jinxin.platform.cdqzsqacs.bean.bo.UserInfo;
import com.jinxin.platform.cdqzsqacs.common.Constant;
import com.jinxin.platform.cdqzsqacs.common.SysOrgInfo;
import com.jinxin.platform.cdqzsqacs.common.SysUserVO;
import com.jinxin.platform.cdqzsqacs.mapper.CdqzsqacsDeviceMapper;
import com.jinxin.platform.cdqzsqacs.mapper.CdqzsqacsOpenRecordMapper;
import com.jinxin.platform.cdqzsqacs.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * @description: (描述...)
 * @return:
 * @author: Linn
 * @time: 2020/05/18
 */
@Component
@Slf4j
public class SysUserRpc {
    @Autowired
    private BusinessDelegate businessDelegate;
    @Autowired
    private CdqzsqacsDeviceMapper deviceMapper;
    /**
     * 获取当前用户对象
     *
     * @return SysUser
     */
    public SysUserVO getCurrentUser() {
        JsonResult result = getJsonResult(Constant.MODULE_KEY,"getCurrentUser");
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getCdqzsqacsCurrentUser:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), SysUserVO.class);
        }
//        else {
//            SysUserVO userVO = new SysUserVO();
//            userVO.setUserId("1");
//            userVO.setUserAccount("admin");
//            userVO.setUserName("admin");
//            return userVO;
//        }
        return null;
    }

    /**
     * 根据当前用户id获取所在组织
     *
     * @return SysUser
     */
    public SysOrgInfo getCurrentOrg() {
        SysUserVO currentUser = getCurrentUser();
        if(currentUser == null){return null; }
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getCurrentOrg");
        HashMap<String, String> map = new HashMap<>();
        map.put("userId",currentUser.getUserId());
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getCurrentOrg:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), SysOrgInfo.class);
        }
//        else {
//            SysOrgInfo userVO = new SysOrgInfo();
//            userVO.setOrgId("1");
//            userVO.setOrgName("一个牛逼的公司");
//            return userVO;
//        }
        return null;
    }

    /**
     * 根据userId获取用户信息
     *
     * @return SysUser
     */
    public UserInfo getUserInfoById(String userId) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("getUserInfoById");
        HashMap<String, String> map = new HashMap<>();
        map.put("userId",userId);
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("getUserInfoById =====>" + result.toString());
        if (result.getSuccess()) {
            if (result.getData() == null) {
                return null;
            }
            log.info("getUserInfoById:" + result.getData());
            return JSON.parseObject(toJSONString(result.getData()), UserInfo.class);
        }
        return null;
    }


    private JsonResult getJsonResult(String keyName,String funName) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(keyName);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName(funName);
        return businessDelegate.invoke(cfg);
    }


    public JsonResult loadCommunityList(String name) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("loadCommunityList");
        HashMap<String, String> map = new HashMap<>();
        map.put("name",name);
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("loadCommunityList =====>" + result.toString());
        if(result.getSuccess()){
            return result;
        }
//        else {
//            List<CommunityInfo> data = new ArrayList<>();
//            for(int i=1;i<=30;i++){
//                CommunityInfo c = new CommunityInfo(i+"","小区"+i);
//                data.add(c);
//            }
//            return JsonResult.ok(data);
//        }
        return null;
    }

    public JsonResult loadBuildingList(String communityId) {
        if(StringUtils.isEmpty(communityId)){
            return JsonResult.error("小区不存在");
        }
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("loadBuildingList");
        HashMap<String, String> map = new HashMap<>();
        map.put("communityId",communityId);
        cfg.setArgs(map);
        JsonResult result = businessDelegate.invoke(cfg);
        if (result.getSuccess()) {
            return result;
//            if(result.getData() == null){
//                return JsonResult.ok(null);
//            }
//            List<BuildingVo> buildingVos = JSON.parseArray(toJSONString(result.getData()), BuildingVo.class);
//            for(BuildingVo buildingVo : buildingVos){
//                String unitData = buildingVo.getUnitData();
//                buildingVo.setData(JSON.parseArray(unitData,UnitInfo.class));
//            }
//            return JsonResult.ok(buildingVos);
        }
//        else {
//            List<BuildingInfo> data = new ArrayList<>();
//            BuildingInfo buildingInfo1 = new BuildingInfo("1","1栋1单元");
//            BuildingInfo buildingInfo2 = new BuildingInfo("2","1栋2单元");
//            data.add(buildingInfo1);
//            data.add(buildingInfo2);
//            return JsonResult.ok(data);
//        }
        return null;
    }

    public JsonResult syncDeviceData() {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("syncDeviceData");
        Map<String, String> argsMap = new HashMap<>();
        argsMap.put("moduleCode",Constant.MODULE_KEY);
        cfg.setArgs(argsMap);
        JsonResult result = businessDelegate.invoke(cfg);
        log.info("智慧社区门禁模块同步设备，返回数据: " + result.toString());
        if (result.getSuccess()) {
            List<CdqzsqacsDevice> deviceList =
                    JSON.parseArray(result.getData().toString(),CdqzsqacsDevice.class);
            int count = 0;
            for (CdqzsqacsDevice device: deviceList){
                CdqzsqacsDevice device1 = deviceMapper.selectByKey(device.getId());
                if(StringUtils.isEmpty(device.getNickName())){
                    device.setNickName(device.getDeviceName());
                }
                if(StringUtils.isEmpty(device.getDeviceNo())){
                    device.setDeviceNo(device.getProductCode());
                }
                if(device1 == null){
                    device.setCreateTime(LocalDateTime.now());
                    deviceMapper.insert(device);
                    count++;
                }else {
                    BeanUtils.copyProperties(device,device1);
                    deviceMapper.updateByKey(device1);
                }
            }
            return JsonResult.ok("成功同步"+count+"条记录","");
        }else {
            return JsonResult.error("同步失败");
        }
    }

    public JsonResult updateDeviceParams(String serialNum) {
        if(StringUtils.isEmpty(serialNum)){
            return JsonResult.error("设备序列号不存在");
        }
        JsonResult result = controlDevice(serialNum, "Update device parameters","{}");
        log.info("更新设备参数: " + result.toString());
        return result;
    }

    private JsonResult controlDevice(String operation, String serialNum,String controlParams) {
        InvokeCfg cfg = new InvokeCfg();
        cfg.setModuleKey(Constant.MODULE_KEY);
        cfg.setClassName(Constant.MODULE_CLASS_NAME);
        cfg.setFunName("controlDevice");
        Map<String, Object> map = new HashMap<>();
        map.put("operation", operation);
        map.put("serialNum", serialNum);
        map.put("controlParams", controlParams);
        cfg.setArgs(map);
        log.info("控制设备的参数: " + controlParams);
        return businessDelegate.invoke(cfg);
    }

}
